const db = require('../db')
const config = require('config')
const uploadService = require('services/upload')

const findById = async (id) => {
  const results = await db('User').where('id', '=', id).select()
  return results[0]
}

const findByOpenId = async (openId) => {
  const results = await db('User').where('wechatOpenId', '=', openId).select()
  return results[0]
}

const bindPhone = async (userId, phone) => {
  const results = await db('User').where('id', '=', userId).update({
    mobile: phone
  })
  return results[0]
}

const registerByOpenId = async (openId, userInfo) => {
  const user = {}
  user.wechatOpenId = openId
  user.nickname = userInfo.nickName
  const uploadRes = await uploadService.uploadRemoteUrl(userInfo.avatarUrl, 'avatar')
  user.avatar = uploadRes.url
  user.gender = userInfo.gender

  const result = await db('User')
    .returning('id')
    .insert(user)

  user.id = result[0]
  return user
}

module.exports = {
  findById,
  findByOpenId,
  bindPhone,
  registerByOpenId
}